// pages/enterprise-management/enterprise-management.ts
import { getUserEnterprise } from '../../../api/enterprise.js';
import { parseFilesJson } from '../../../api/enterprise.js';
import { PAGES, goToPage } from '../../../config/pages';

Page({
  data: {
    enterprise: null as any,
    files: [] as any[],
    loading: true,
    statusMap: {
      '0': { text: '审核中', color: '#ff9500' },
      '1': { text: '已认证', color: '#00a870' },
      '2': { text: '审核未通过', color: '#e34d59' }
    }
  },

  onLoad() {
    this.loadEnterpriseInfo();
  },

  onShow() {
    // 每次显示时刷新数据
    this.loadEnterpriseInfo();
  },

  async loadEnterpriseInfo() {
    wx.showLoading({ title: '加载中...' });
    
    try {
      const result = await getUserEnterprise();
      console.log('获取企业信息:', result);
      
      if (result.status === 200 && result.data && result.data.enterprise) {
        const enterpriseData = result.data.enterprise;
        
        // 处理企业状态
        const status = String(enterpriseData.status || '0');
        const statusInfo = this.data.statusMap[status as '0' | '1' | '2'] || { text: '未知', color: '#999' };
        
        // 构建显示数据
        const displayData = {
          id: enterpriseData.id,
          name: enterpriseData.name || '未设置',
          shortName: enterpriseData.name ? enterpriseData.name.substring(0, 2) : '企业',
          type: `${enterpriseData.tags || '未设置'} · ${enterpriseData.nature || '未设置'}`,
          category: enterpriseData.tags || '未设置',
          financing: enterpriseData.funding_stage || '未设置',
          scale: enterpriseData.staff_size || '未设置',
          nature: enterpriseData.nature || '未设置',
          status: enterpriseData.status,
          statusText: statusInfo.text,
          statusColor: statusInfo.color,
          contact: enterpriseData.contact_name || '未设置',
          phone: enterpriseData.contact_phone || '未设置',
          address: enterpriseData.address || '未设置',
          description: enterpriseData.description || '暂无描述',
          logo_files: enterpriseData.logo_files,
          license_file: enterpriseData.license_file,
          cert_file: enterpriseData.cert_file,
          agent_file: enterpriseData.agent_file
        };
        
        // 构建文件列表
        const files = [];
        
        // 营业执照
        if (enterpriseData.license_file) {
          const licenseFiles = parseFilesJson(enterpriseData.license_file);
          if (licenseFiles.length > 0) {
            files.push({
              name: '营业执照',
              url: licenseFiles[0],
              type: 'image',
              icon: 'fa-file-image'
            });
          }
        }
        
        // 认证体系文件
        if (enterpriseData.cert_file) {
          const certFiles = parseFilesJson(enterpriseData.cert_file);
          if (certFiles.length > 0) {
            files.push({
              name: '认证体系文件',
              url: certFiles[0],
              type: 'image',
              icon: 'fa-file-image'
            });
          }
        }
        
        // 代理证书
        if (enterpriseData.agent_file) {
          const agentFiles = parseFilesJson(enterpriseData.agent_file);
          if (agentFiles.length > 0) {
            files.push({
              name: '代理证书',
              url: agentFiles[0],
              type: 'image',
              icon: 'fa-file-image'
            });
          }
        }
        
        this.setData({
          enterprise: displayData,
          files,
          loading: false
        });
      } else {
        wx.showToast({
          title: '暂无企业信息',
          icon: 'none'
        });
        this.setData({
          loading: false
        });
      }
    } catch (error: any) {
      console.error('加载企业信息失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加载失败'),
        icon: 'none'
      });
      this.setData({
        loading: false
      });
    } finally {
      wx.hideLoading();
    }
  },

  editEnterprise() {
    wx.showModal({
      title: '编辑企业信息',
      content: '即将跳转到企业信息编辑页面',
      success: (res) => {
        if (res.confirm) {
          goToPage(PAGES.EDIT_COMPANY);
        }
      },
    });
  },

  manageCertification() {
    wx.showToast({
      title: '认证管理功能开发中...',
      icon: 'none',
    });
  },

  previewFile(e: any) {
    const { index } = e.currentTarget.dataset;
    const file = this.data.files[index];
    
    if (file && file.url) {
      // 预览图片
      wx.previewImage({
        current: file.url,
        urls: [file.url]
      });
    } else {
      wx.showToast({
        title: '文件不存在',
        icon: 'none',
      });
    }
  },

  downloadFile(e: any) {
    const { index } = e.currentTarget.dataset;
    const file = this.data.files[index];
    
    if (file && file.url) {
      wx.downloadFile({
        url: file.url,
        success: (res) => {
          if (res.statusCode === 200) {
            wx.showToast({
              title: '下载成功',
              icon: 'success'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '文件不存在',
        icon: 'none',
      });
    }
  },
});

